package mysql

import (
	"gorm.io/gorm"
	"video-joy/userrpc/userrpc"
)

type CollectionInfo struct {
	gorm.Model
	UserId        int `gorm:"type:int(11);not null"`
	VideoId       int `gorm:"type:int(11);not null"`
	CollectStatus int `gorm:"type:int(11);not null"`
}

func (i *CollectionInfo) CollectionAdd(db *gorm.DB) error {
	return db.Debug().Create(i).Error
}

func (i *CollectionInfo) CollectionFindById(db *gorm.DB, userId int64, videoId int64) error {
	return db.Debug().Where("collection_infos.user_id=?", userId).Where("collection_infos.video_id=?", videoId).Find(i).Error
}

func (i *CollectionInfo) CollectionDel(db *gorm.DB) error {
	return db.Debug().Delete(i).Error
}

func (i *CollectionInfo) FindCollectionById(db *gorm.DB, id int64) error {
	return db.Debug().Where("collection_infos.id=?", id).First(i).Error
}

/*
SELECT
  collection_infos.*,
  collection_infos.id as collection_id,
  video_infos.cover_link,
  video_infos.video_title,
  user_infos.id,
  video_infos.play_num
FROM
  collection_infos
  LEFT JOIN user_infos ON collection_infos.user_id = user_infos.id
  LEFT JOIN video_infos ON collection_infos.video_id=video_infos.id
*/

func CollectionList(db *gorm.DB, in *userrpc.CollectionListRequest) []*userrpc.CollectionList {
	var collectionlist []*userrpc.CollectionList

	db.Debug().Model(&CollectionInfo{}).
		Select(
			"collection_infos.*",
			"collection_infos.id as collection_id",
			"video_infos.cover_link",
			"video_infos.video_title",
			"user_infos.id",
			"video_infos.play_num").
		Joins("LEFT JOIN user_infos ON collection_infos.user_id = user_infos.id").
		Joins("LEFT JOIN video_infos ON collection_infos.video_id=video_infos.id").
		Where("collection_infos.user_id=?", in.UserId).
		Order("collection_infos.created_at desc").
		Scopes(Paginate(int(in.Page), int(in.PageSize))).
		Find(&collectionlist)

	return collectionlist
}
